/*
 * @Author: ZL
 * @Date:   2019/05/15
 * @Last Modified by:   ZL
 * @Last Modified time: $ $
 */
var vm = new Vue({
  el: '#portal',
  data: function () {
    var _that = this;
    var checkSame = function (rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== _that.editPasswordData.newPassword) {
        callback(new Error('两次输入密码不一致！'));
      } else {
        callback();
      }
    };
    var checkDiffer = function (rule, value, callback) {

        //密码包含 数字,英文,字符中的两种以上，长度8-20
        //"^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{9,20}$"
        var patrn = "(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{9,20}";
        var re = new RegExp(patrn);
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (value == _that.editPasswordData.oldPassword) {
        callback(new Error('新密码和原密码不能相同！'));
      } else if(!checkPwd(value)){
        callback(new Error('密码需含数字、小写字母、大写字母、特殊符号中的三种,长度9-20'));
      }else{
	     callback();
	  }	  
    };
    function checkPwd(pwd) {
        var res = false;
        if(pwd==""||checkStrong(pwd)  <  3) {
            res = false;
        }else{
            res = true;
        }
        return res;
    }
    function  checkStrong(sPW)  {
        if  (sPW.length  <  9||sPW.length  >  20)
            return  0;  //密码太短或太长
        Modes  =  0;
        for  (i  =  0;  i  <  sPW.length;  i++)  {
            //测试每一个字符的类别并统计一共有多少种模式.
            Modes  |=  CharMode(sPW.charCodeAt(i));
        }
        return  bitTotal(Modes);
    }

    function  CharMode(iN){
        if  (iN>=48  &&  iN  <=57)  //数字
            return  1;
        if  (iN>=65  &&  iN  <=90)  //大写
            return  2;
        if  (iN>=97  &&  iN  <=122)  //小写
            return  4;
        else
            return  8;
    }

    function  bitTotal(num)  {
        modes  =  0;
        for  (i  =  0;  i  <  4;  i++)  {
            if  (num  &  1)  modes++;
            num  >>>=  1;
        }
        return  modes;
    }
    var checkOldPass = function (rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入原密码'));
      } else {
        request('opus-admin', {
          url: ctx+'opus/front/om/users/passwordCheckout',
          data: {oldPassword: value},
          type: 'get'
        }, function (data) {
          if(data.success){
            callback();
          }else {
            callback(new Error(data.message ? data.message : '原密码错误'));
          }
        })
      }
    };
    return {

      headerData: [], // 头部菜单所有data
      leftData: [],  // 左侧菜单data
      headerActive: 0,  // 头部菜单active状态
      curWidth: (document.documentElement.clientWidth || document.body.clientWidth),//当前屏幕宽度
      curHeight: (document.documentElement.clientHeight || document.body.clientHeight),//当前屏幕高度
      showMenuMore: false,  // 展示更多菜单默认隐藏
      menuCount: 1, // 头部菜单展示条数 menuCount+1
      loginName: '', // 用户登陆名
      userName: '', // 用户名
      userId: '',  // 用户id
      activeTabIframe: '', // 顶部选项卡 绑定active
      activeTabData: [], // 顶部选项卡 所有展示的tab
      tabIndex: [], // 顶部选项卡 所有展示的tab的key
      hideHeaderData: [], // 头部菜单展示data
      headerDataShow: [], // 头部菜单隐藏data
      showMoreItem: false, // 是否展示隐藏的头部菜单
      leftMenuActive:0, // 左侧菜单active
      editUserInfoFlag: false, // 是否展示个人信息topbar
      showUserInfo: false, // 是否展示个人信息弹窗
      editPasswordFlag: false, // 是否展示修改密码弹窗
      editPasswordData: {
        oldPassword:'',
        newPassword: '',
        newPasswordCheck: ''
      }, // 修改密码data
      newPasswordCheck: '', // 再次确认新密码
      editPasswordRule: {
        oldPassword: [
          { validator: checkOldPass, required: true, trigger: 'blur' },
        ],
        newPassword: [
          { validator: checkDiffer, required: true, trigger: 'blur' }
        ],
        newPasswordCheck: [
          { validator: checkSame, required: true,trigger: 'blur' }
        ]
      },  // 修改密码校验
      topOrgId: '',
      userSex: '',
      userEmail: '',
      showTabOpt: false,
      tabOptTop: '',
      tabOptleft: '',
      tabId: '',
      tabKey: '',
      leftClosed: false,
      isFullScreen: true,
      intervalTime: null, // 定时获取消息条数周期
      messgeCount: 0,
      ctx: ctx,
      portalTitle:null,
      portalLogoUrl:null,
      activeTabSelData: {}, // addTab新开窗口的数据
      logoutSrc: [], // 退出登录列表
      logoutIframe: false, // 是否退出
    }
  },
  mounted: function () {
    var _that = this;
    window.addEventListener("resize", function() {
      vm.curWidth=document.documentElement.clientWidth;
      vm.curHeight = document.documentElement.clientHeight;
      vm.setHeaderShow();
      if (!_that.checkFull()) {
        _that.isFullScreen=true;
      }else {
        _that.isFullScreen=false;
      }
    });
    //在document挂载onlick事件
    document.addEventListener("click",this.displayMenuPopover)
    // 监听子页面的传递过来的数据
    if(window.addEventListener){
      window.addEventListener('message',_that.onMessage,false);
    }else{
      if(window.attachEvent){
        window.attachEvent("onmessage", _that.onMessage);
      }
    }
    _that.getUserIndo();
    _that.getCountAoaMsgRangeForMyReceive();
    setInterval(function(){
      _that.getCountAoaMsgRangeForMyReceive();
    },30000);
    //获取门户标题及logo url
    _that.initPortal();
  },
  watch: {
    intervalTime: function(){
      var _that = this;
      setInterval(function(){
        _that.getViewDataCountByViewCode(_that.leftData);
      },_that.intervalTime)
    }
  },
  methods: {
    //获取门户标题及logo url
    initPortal: function(){
        var _that = this;
        request('opus-front', {
            url: ctx+'opus/front/config',
            type: 'get',
        }, function (data) {
            if(data.success){
                _that.portalTitle = data.content.title;
                if(_that.portalTitle!=null)
                  $("title").html(_that.portalTitle);
                _that.portalLogoUrl = data.content.logoUrl;
            }
        }, function (msg) {
            alertMsg('', '服务请求失败', '关闭', 'error', true);
        });
    },
    getUserIndo: function () { // 获取用户登陆信息
      var _that = this;
      request('opus-admin', {
        url: ctx+'opus/front/om/users/currOpusLoginUser',
        type: 'get',
      }, function (data) {
        if(data.success){
          _that.loginName = data.content.user.loginName;
          _that.userName = data.content.user.userName;
          _that.userId = data.content.user.userId;
          _that.topOrgId = data.content.currentOrgId
          _that.getHeaderData();
          _that.getUserAllInfo(data.content.user.loginName);
          _that.getLogoutUrls();
        }
      }, function (msg) {
        alertMsg('', '服务请求失败', '关闭', 'error', true);
      });
    },
    getUserAllInfo: function(loginName){ // 获取登录用户所有信息
      var _that = this;
      request('agx', {
        // url: '../../../../../static/agcloud/framework/ui-schemes/default/js/user_2.json',
        url: ctx + 'opus/front/om/users',
        type: 'get',
        data: {loginName: loginName}
      }, function (data) {
        if(data.success){
          _that.userEmail = data.content.userEmail;
          _that.userSex = data.content.userSex;
        }
      }, function (msg) {
        alertMsg('', '服务请求失败', '关闭', 'error', true);
      });
    },
    getHeaderData: function () { // 获取菜单数据
      var _that = this;
      var props = {
        isTree: 'true',
        netName: '前端网络入口',
        tmnId: '1',
        topOrgId: _that.topOrgId,
        userId: _that.userId
      };
      var _that = this;
      request('opus-admin', {
        url: ctx+'opus/front/om/users/user/'+_that.userId+'/allMenus',
        type: 'get',
        data: props
      }, function (data) {
        _that.headerData = data.content;
        _that.setHeaderShow();
        if(data.content && data.content.length>0){
          if(data.content[0].childrenList){
            _that.leftData = data.content[0].childrenList;
            _that.activeTabData.push({
              menuName: _that.leftData[0].menuName,
              id: _that.leftData[0].id,
              menuInnerUrl: _that.leftData[0].menuInnerUrl
            });
            _that.tabIndex.push(_that.leftData[0].id);
          }else {
            _that.activeTabData.push({
              menuName: data.content[0].menuName,
              id: data.content[0].id,
              menuInnerUrl: data.content[0].menuInnerUrl
            });
            _that.tabIndex.push(data.content[0].id);
          }
          _that.activeTabIframe =  _that.activeTabData[0].id;
          _that.$nextTick(function(){
            _that.menuAddActive();
          });
          _that.getViewDataCountByViewCode(_that.leftData);
        }
      }, function (msg) {
        alertMsg('', '服务请求失败', '关闭', 'error', true);
      });
    },
    setHeaderShow: function () {  // 设置头部可展示菜单长度
      var _that = this;
      var logoWidth = $('.protal-header .subsystem-name').outerWidth(true);
      var topbarWidth = $('.user-info-topbar').outerWidth(true);
      var width = _that.curWidth - logoWidth - topbarWidth;
      if (_that.headerData !== null && _that.headerData.length > 0) {
        var  count = parseInt(width/140);
        if(count < _that.headerData.length && count>0){
          _that.showMenuMore = true;
          _that.menuCount = count - 1;
        }else if(count<0 || count==0) {
          _that.showMenuMore = true;
          _that.menuCount = 0;
        }else {
          _that.showMenuMore = false;
          _that.menuCount = _that.headerData.length;
        }
      } else {
        _that.showMenuMore = false;
        _that.menuCount = _that.headerData.length;
      }
      _that.initMenuCount(_that.headerData, _that.menuCount)
    },
    initMenuCount: function (eleLi, n) {  // 重置头部菜单
      if(eleLi){
        this.headerDataShow=eleLi.slice(0,n);
        this.hideHeaderData = eleLi.slice(n)
      }
    },
    headerChangeMenu: function (data, index,e) { // 头部菜单点击事件
      var _that = this;
      if(!data.childrenList){
        _that.addTab(e,data,this.activeTabIframe,index)
      }else {
        _that.headerActive = index;
        _that.leftData = data.childrenList;
        _that.showMoreItem = false;
        _that.leftMenuActive = -1;
        _that.getViewDataCountByViewCode(_that.leftData);
        _that.$nextTick(function(){
          _that.menuAddActive();
        })
        $(e.srcElement).addClass('m-menu__item--active').siblings('.m-menu__item--active').removeClass('m-menu__item--active');
        $(e.srcElement).parents('.m-menu__item').addClass('m-menu__item--active').siblings('.m-menu__item--active').removeClass('m-menu__item--active');
      
      }
    },
    addTab: function (ev,data,activeTab,ind,openFlag) { // 点击新增顶部tab  openFlag打开方式
      ev.cancelBubble = true;
      this.leftMenuActive = ind;
      this.activeTabSelData = data;
      if(openFlag=='win'){
        window.open(data.menuInnerUrl);
        return false;
      };
      if(!data.childrenList&&(this.tabIndex.indexOf(data.id) == -1)){
        this.activeTabData.push({
          menuName: data.menuName,
          id: data.id,
          menuInnerUrl: data.menuInnerUrl
        });
        this.activeTabIframe = data.id;
        this.menuAddActive();
        this.tabIndex.push(data.id);
      }else {
        this.activeTabIframe = data.id;
        this.menuAddActive();
      }
    },
    removeTab: function (targetName) { // 移除顶部tab
      var tabs = this.activeTabData;
      var activeName = this.activeTabIframe;
      var _that = this;
      this.showTabOpt = false;
      if (activeName === targetName) {
        tabs.forEach(function (tab, index) {
          if (tab.id === targetName) {
            var nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.id;
            }
          }
        });
      }
      _that.activeTabIframe = activeName;
      _that.menuAddActive();
      _that.activeTabData = tabs.filter( function (tab) { return tab.id !== targetName});
      _that.tabIndex = [];
      _that.activeTabData.forEach(function(e){
        _that.tabIndex.push(e.id);
      });
    },
    tabMouseRightClick:function(ev){ // 顶部tab 右击事件
      ev.cancelBubble = true;
      if(ev.path){
        this.tabId = ev.path[0].id;
        this.tabKey = ev.path[0].id.split('tab-')[1];
      }else {
        this.tabId = ev.srcElement.id
        this.tabKey = ev.srcElement.id.split('tab-')[1];
      }
      if(!(this.tabId.indexOf('tab-MENU_') > -1)){
        return false;
      }else {
        this.showTabOpt = true;
        this.tabOptTop = ev.offsetY;
        if($('body').hasClass('demo2')){
          this.tabOptleft = ev.clientX - 90;
        }else {
          this.tabOptleft = ev.clientX - 170;
        }
        this.activeTabIframe = this.tabKey;
        this.menuAddActive();
      }
    },
    closeOther: function () { // 移除其他顶部tab
      var start = this.tabIndex.indexOf(this.tabKey);
      this.tabIndex = this.tabIndex.slice(start,start+1);
      this.activeTabData = this.activeTabData.slice(start,start+1);
      this.showTabOpt = false;
    },
    closeLeft: function () { // 移除左边顶部tab
      var start = this.tabIndex.indexOf(this.tabKey);
      this.tabIndex = this.tabIndex.slice(start);
      this.activeTabData = this.activeTabData.slice(start);
      this.showTabOpt = false;
    },
    closeRight: function () { // 移除右边顶部tab
      var start = this.tabIndex.indexOf(this.tabKey);
      this.tabIndex = this.tabIndex.slice(0,start+1);
      this.activeTabData = this.activeTabData.slice(0,start+1);
      this.showTabOpt = false;
    },
    changeTab: function(){  // tab点击事件
      var tabEle = $('.el-tabs__content .el-tab-pane');
      var tabEleLen = tabEle.length;
      var _that = this;
      _that.menuAddActive();
    },
    changeLeftClosed: function (flag) { // 左边栏展开收缩事件
      if(flag){
        this.leftClosed = false
      }else {
        this.leftClosed = true
      }
    },
    displayMenuPopover:function () { // 隐藏tab操作窗口
      this.showTabOpt = false;
    },
    onMessage:function (e) {
      var _that = this
      var data = e.data
      if(!data.vueDetected&&data.id!=undefined){
        data.menuInnerUrl = e.origin + data.menuInnerUrl
        _that.addTab(e,data,'MENU_'+data.id,_that.leftMenuActive++);
      }
    },
    // 获取登出地址
    getLogoutUrls:function(){
      var _that = this;
      request('opus-admin', {
        url: ctx+'opus/front/om/users/listLogoutUrl',
        type: 'get',
        data: {
            netName : '前端网络入口',
            orgId: _that.topOrgId,
            userId : _that.userId
        }
      }, function (result) {
        if (result.success) {
            _that.logoutSrc = result.content;
        }else{
            _that.logoutSrc = [];
        }
      }, function (msg) {
        // 获取登出地址失败

      });
    },
    logout: function (e) { // 退出登陆
      e.cancelBubble = true;
      var _that = this;
      confirmMsg('', '确定要退出登陆吗？', function () {
        _that.logoutIframe = true;
        _that.$nextTick(function(){
          setTimeout(function () {
            window.location.href = ctx+ 'logout';
          },500);
        });
      },function () {
        _that.logoutIframe = false;
      })
    },
    editPasswordSubmit: function(){ // 修改密码
      var _that = this;
      _that.$refs['editPasswordData'].validate(function (valid) {
        if (valid) {
          var props = {
            newPassword: _that.editPasswordData.newPassword,
            oldPassword: _that.editPasswordData.oldPassword,
          };
          request('opus-admin', {
            url: ctx+'opus/front/om/users/password',
            data: props,
            type: 'post'
          }, function (data) {
            if(data.success){
              _that.$message({
                message: '密码修改成功',
                type: 'success'
              });
              _that.editPasswordFlag = false;
            }else {
              _that.$message({
                message: data.message ? data.message : '密码修改失败',
                type: 'error'
              });
            }
          },function(msg){
            _that.$message({
              message: msg.message ? msg.message : '密码修改失败',
              type: 'error'
            });
          })
        } else {
          alertMsg('', '请输入完整且正确的信息', '关闭', 'warning', true);
          return false;
        }
      });
    },
    clearDialogData: function(formName){ // 清空表单
      this.$refs[formName].resetFields();
    },
    toggleFullScreen: function () { // 切换全屏
      if(this.isFullScreen){
        this.enterfullscreen()
      }else {
        this.exitfullscreen();
      }
    },
    enterfullscreen:function() {//进入全屏
      var docElm = document.documentElement;
      //W3C
      if (docElm.requestFullscreen) {
        docElm.requestFullscreen();
      }
      //FireFox
      else if (docElm.mozRequestFullScreen) {
        docElm.mozRequestFullScreen();
      }
      //Chrome等
      else if (docElm.webkitRequestFullScreen) {
        docElm.webkitRequestFullScreen();
      }
      //IE11
      else if (docElm.msRequestFullscreen) {
        docElm.msRequestFullscreen();
        var widthFull = $(window).width();
        $('#wrapper').css('width',widthFull);
      }else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
          wscript.SendKeys("{F11}");
        }
      }
      this.isFullScreen = true;
    },
    exitfullscreen: function () { //退出全屏
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
      else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      }
      else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      }
      else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
          wscript.SendKeys("{F11}");
        }
      }
      this.isFullScreen = false;
    },
    checkFull: function() { // 判断是否全屏
      var isFull = document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled;
      if (isFull === undefined) {isFull = false;}
      return isFull
    },
    showEditUserInfo: function () { // 是否展示login-info
      this.editUserInfoFlag = !this.editUserInfoFlag;
    },
    menuAddActive: function(){
      $('.protal-content-left .el-menu-item').removeClass('is-active');
      $('#'+this.activeTabIframe).addClass('is-active').siblings('.el-menu-item').removeClass('is-active');
    },
    getViewDataCountByViewCode:function(leftData) {
      var totalCount = 0;
      var _that = this;
      if(leftData.length==0){return false}
      leftData.map(function(e){
        if(e.openMenuCount){
          _that.intervalTime = e.menuCountInterval;
          request('opus-admin', {
            url: ctx + e.menuCountUrl,
            type: 'get',
          }, function (data) {
            if(data){
              e.subCount = data;
            }
          }, function (msg) {
            _that.$message({
              message: '服务请求失败',
              type: 'error'
            });
          });
        } else if(e.childrenList) {
          _that.getViewDataCountByViewCode(e.childrenList);
        }
      });
    },
    getCountAoaMsgRangeForMyReceive: function () {
      var _that = this;
      request('opus-admin', {
        url: ctx+'rest/aoa/msg/range/getCountAoaMsgRangeForMyReceiveUnReaded',
        type: 'post',
      }, function (data) {
        _that.messgeCount = data.content;
      });
    }
  }
});